package com.cenxi.config;


import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.cenxi.utils.constants.CommonFieldsConstants;
import com.cenxi.utils.constants.Constants;
import com.cenxi.utils.subject.SecurityContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author dijia
 * @date 2022/10/18
 */
@Slf4j
@Configuration
public class MybatisObjectHandler implements MetaObjectHandler {

    /**
     * 分页插件
     *
     * @return
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }


    @Override
    public void insertFill(MetaObject metaObject) {
        //创建时间填入
        if (Objects.isNull(this.getFieldValByName(CommonFieldsConstants.CREATE_TIME, metaObject))) {
            this.setFieldValByName(CommonFieldsConstants.CREATE_TIME, LocalDateTime.now(), metaObject);
        }

        //更新时间填入
        if (Objects.isNull(this.getFieldValByName(CommonFieldsConstants.UPDATE_TIME, metaObject))) {
            this.setFieldValByName(CommonFieldsConstants.UPDATE_TIME, LocalDateTime.now(), metaObject);
        }

        //更新人填入
        if (Objects.isNull(this.getFieldValByName(CommonFieldsConstants.UPDATE_BY, metaObject))) {
            this.setFieldValByName(CommonFieldsConstants.UPDATE_BY, SecurityContextUtil.getLoginUser().getNickName(), metaObject);
        }

        //创建人填入
        if (Objects.isNull(this.getFieldValByName(CommonFieldsConstants.CREATE_BY, metaObject))) {
            this.setFieldValByName(CommonFieldsConstants.CREATE_BY, SecurityContextUtil.getLoginUser().getNickName(), metaObject);
        }

        //删除标识符插入
        if (Objects.isNull(this.getFieldValByName(CommonFieldsConstants.DELETE_FLAG, metaObject))) {
            this.setFieldValByName(CommonFieldsConstants.DELETE_FLAG, 1, metaObject);
        }


    }

    @Override
    public void updateFill(MetaObject metaObject) {
        //更新时间填入
        this.setFieldValByName(CommonFieldsConstants.UPDATE_TIME, LocalDateTime.now(), metaObject);
        //更新人填入
        this.setFieldValByName(CommonFieldsConstants.UPDATE_BY, SecurityContextUtil.getLoginUser().getNickName(), metaObject);
    }
}
